<?php

/**
 * Created by PhpStorm.
 * @property  cart
 * @author: 汤文辉
 * @since: 2017/6/18 9:50
 * 购物车类，进行购物车里图书的添加和删除操作：
 * array AlterBook($book_id)    根据图书编号进行添加或修改
 * void delete($book_id)      删除购物车里选定的图书
 */
include_once '../config/Config_mysqlcon.php';
class Book_Cart{
    /**
     * Book_Cart constructor.
     */
    function __construct()
    {
        global $con;
        $this->con = $con;
    }

    /**
     * 添加书籍，根据记录是否存在选择添加记录或是修改数量
     * @param $book_id
     * @return array $this->cart
     */
    function AlterBook($book_id){
        if($this->con && $book_id){
            $this->cart["$book_id"]['book_num'] = $_POST["book_num"];
            $user_id = $_COOKIE["user_login"];
            $num = $_POST["book_num"];
            //根据数据库中是否存在当前书籍来进行数量的添加或者记录的添加
            $sql = "select count(*) from book_cart where user_id='$book_id'";
            if($result = mysqli_query($this->con,$sql)){  //已经存在，只需修改数量
                $sql = "update book_cart set num = '$num' where book_id = '$book_id'";
                mysqli_query($this->con,$sql);
            }else{                                       //否则，需要添加新的记录
                $sql = "insert into book_cart(user_id,book_id,num) values('$user_id','$book_id','$num')";
                mysqli_query($this->con,$sql);
            }
        }
        return $this->cart;
    }
    /**
     * 删除购物车中的书籍和相关订单中的信息
     * @param $book_id
     */
    function delete($book_id){
        $user_id =$_COOKIE["user_login"];
        if($this->con && $book_id){
//            $sql1 = "select order_id from book_order where book_id = '$book_id'";//查找订单号用于查找和删除
            //下面根据查找到的订单号删除order，user_order表中的相关记录
//            if($result1 = mysqli_query($this->con,$sql1)){
//                while ($order = $result1->fetch_row()){
//                    $order_id = $order[0];
//                    $sql2 = "delete from order,user_order where order_id = '$order_id'";
//                    mysqli_query($this->con,$sql2);
//                }
//            }
            $sql3 = "delete  from book_cart  where book_id = '$book_id' AND user_id = ";//最后删除book_cart,book_order表中的相关数据
            mysqli_query($this->con,$sql3);
            //删除购物车里的相关书籍信息
            if(array_key_exists($book_id, $this->cart)){
                $keys = array_keys($this->cart);
                $index = array_search($book_id, $keys);
                if($index != FALSE){
                    array_slice($this->cart, $index, 1);
                }
            }
        }

    }

}